package com.candicom.race.gui;

import com.candicom.race.cars.AbstractCar;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class MyCanvas extends JFrame {

    private final OuterCanvas outerCanvas;
    private final InnerCanvas innerCanvas;

    public MyCanvas(Dimension _dim, Image _image) {
        super("2D Car Race");
        outerCanvas = new OuterCanvas(_dim, _image);
        innerCanvas = new InnerCanvas(_dim);
        outerCanvas.setInnerCanvas(innerCanvas);
        add(outerCanvas);
        pack();
        setLocationRelativeTo(null);
        setResizable(false);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public void drawCars(AbstractCar _car1, AbstractCar _car2) {
        Point loc1 = _car1.getLocation();
        Point loc2 = _car2.getLocation();

        innerCanvas.putCars(
                loc1.x, loc1.y, (_car1.getAngle() == 0) ? _car1.getImage() : rotate(_car1.getAngle(), _car1.getImage()),
                loc2.x, loc2.y, (_car2.getAngle() == 0) ? _car2.getImage() : rotate(_car2.getAngle(), _car2.getImage())
                );
    }

    private BufferedImage rotate(int _angle, Image _image) {
        int width = _image.getWidth(null);
        int height = _image.getHeight(null);

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gImage = (Graphics2D) image.getGraphics();
        gImage.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gImage.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        gImage.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        AffineTransform origXform = gImage.getTransform();
        AffineTransform newXform = (AffineTransform) (origXform.clone());

        //center of rotation is center of the panel        
        newXform.rotate(Math.toRadians(_angle), width / 2, height / 2);
        gImage.setTransform(newXform);
        gImage.drawImage(_image, null, null);
        gImage.setTransform(origXform);
        gImage.dispose();

        return image;

    }
}
